package top.tagao.study02_Set;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;

/**
 * @author fu-xiao-liu
 * @Date 2022/4/15 16:20
 */
public class study_01_HashSet {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();

        Dog x1 = new Dog(1001,"AA");
        Dog x2 = new Dog(1002,"BB");
        hashSet.add(x1);
        hashSet.add(x2);
        System.out.println(x1.hashCode());
        x1.name = "cc";

        //删除失败。因为(1001,"CC")的哈希值对应位置为空。虽然此时p1为(1001,"CC")，删除时会计算(1001,"CC")哈希值,此时哈希表中这个位置没有值，所以删除失败。
        hashSet.remove(x1);

        //添加成功。因为(1001,"CC")的哈希值对应位置为空。虽然集合中已有(1001,"CC")，但集合中的(1001,"CC")哈希值对应位置还是(1001,"AA")计算得来的，"CC"只是由"AA"修改得来的
        hashSet.add(new Dog(1001,"CC"));;

        //添加成功。因为此时集合中没有元素equal=(1001,"AA")。虽然集合中第一个(1001,"CC")的哈希值对应位置和(1001,"AA")一致，但equals()不同。(1001,"AA")会挂在(1001,"CC")链表的的后面
        hashSet.add(new Dog(1001,"AA"));

        System.out.println(hashSet);

    }
}

class Dog{
    int id;
    String name ;

    public Dog(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Dog dog = (Dog) o;

        if (id != dog.id) return false;
        return name != null ? name.equals(dog.name) : dog.name == null;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}